package com.kdtech.analyse.app;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.StringUtils;
import com.kdtech.analyse.AnalyseNews;

/**
 * @name 虎嗅网
 * @link http://www.huxiu.com/
 */
public class HuxiuAppAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://.*.huxiu.com/article/[0-9]*/1.html.*",
		"http://.*.huxiu.com/group/thread/[0-9]*",
	};


	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		
		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		
		title =doc.select("h1.t-h1").text();
		if(StringUtils.isBlank(title))
			title =doc.select("div.wrap-left h1").text();
		if(StringUtils.isBlank(title))
			title =doc.select("div.neirong h1").text();
		
		date=DateUtils.matchDate(doc.select("span.article-time").text());
		if(date==null)
			date=DateUtils.matchDate(doc.select("time.pull-left").text());
		if(date==null)
			date=DateUtils.matchDate(doc.select("div.other").text());
		
		content =HtmlCleaner.getContentHtml(url, doc.select("div.article-content-wrap"));
		if(StringUtils.isBlank(content))
			content =HtmlCleaner.getContentHtml(url, doc.select("div.article-content-box"));
		if(StringUtils.isBlank(content))
			content =HtmlCleaner.getContentHtml(url, doc.select("td#article_content"));
		
		Elements authorList = doc.select("span.author-name");
		if(authorList.size() == 0)
			authorList = doc.select("div.mob-right div a");
		if(authorList.size() == 0)
			authorList = doc.select("div.other u");
		if(authorList.size() > 0)
			author = authorList.get(0).text();
		if(StringUtils.isNotBlank(author) && author.indexOf("本文作者：")!=-1)
			author = StringUtils.substringAfter(author, "本文作者：");
			
		
		news.setTitle(StringUtils.trimSpace(title));
		news.setAuthor(author);
		news.setContent(content);
		news.setDate(date);

		return news;

	}

	

	

	
}

